package servlet;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import dao.CartDao;
import dao.OrderDao;
import entity.Cart;
import entity.CartItem;
import entity.Order;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@WebServlet("/addOrders")
public class AddOrdersServlet extends HttpServlet {
	
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {

		System.out.println("-----------addOrders------------");
		User user = (User) request.getSession().getAttribute("user");
		// 获取选中的收货地址
		String selectedUserAddress = request.getParameter("selectedUserAddress");
		// 获取提交的 JSON 数组字符串
		String[] cartItems = request.getParameterValues("cartItem[]");
		List<Order> orderList = new ArrayList<>();
		// 使用 Gson 将 JSON 数组字符串解析为 List<CartItem>
		Gson gson = new Gson();
		List<CartItem> cartItemList = new ArrayList<>();
		for (String item : cartItems) {
			CartItem cartItem = gson.fromJson(item, CartItem.class);
			cartItemList.add(cartItem);
		}
		// 处理接收到的商品信息
		for (CartItem cartItem : cartItemList) {
			Integer cartId = cartItem.getCartId();
			CartDao cartDao = new CartDao();
			Cart cart = cartDao.selectByCartId(String.valueOf(cartId));
			Integer state = 0;
			LocalDateTime currentTime = LocalDateTime.now();
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			String createTime = currentTime.format(formatter);
			Order order = new Order();
			order.setOrderId(generateOrderNumber());
			order.setUserId(user.getUserId());
			order.setGoodsId(cart.getGoodsId());
			order.setGoodsName(cart.getGoodsName());
			order.setGoodsImage(cart.getGoodsImage());
			order.setNote(cart.getNote());
			order.setPrice(cart.getGoodsPrice());
			order.setQty(cart.getQty());
			order.setOrderSum(cart.getCartSum());
			order.setAddress(selectedUserAddress);
			order.setState(state);
			order.setCreateTime(createTime);
			order.setUpdateTime(createTime);
			OrderDao dao = new OrderDao();
			int ret = dao.addOrder(order);
			orderList.add(order);
			//删除购物车的信息
			if(ret == -1) {
				response.sendRedirect("error.jsp");
			}
			int deleteRet = cartDao.deleteByIdCart(cartId);
			if(deleteRet == -1) {
				response.sendRedirect("error.jsp");
			}
		}
		request.getSession().setAttribute("myNewOrders",orderList);
		response.sendRedirect("frontend/fin-order2.jsp");
	}

	public static String generateOrderNumber() {
		int length = 15;
		StringBuilder sb = new StringBuilder(length);
		Random random = new Random();

		// 可选的字符集合，包含0-9和A-Z
		String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

		for (int i = 0; i < length; i++) {
			// 从字符集合中随机选择一个字符
			char randomChar = characters.charAt(random.nextInt(characters.length()));
			sb.append(randomChar);
		}

		return sb.toString();
	}


}
